package com.zdkj.subway.st.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.entity.SwStPlanMonth;
import com.zdkj.subway.st.entity.SwStPlanWeek;
import com.zdkj.subway.st.service.SwStPlanMonthService;
import com.zdkj.subway.st.service.SwStPlanWeekService;
import com.zdkj.subway.st.util.LocalDateConverter;
import com.zdkj.subway.st.util.LocalDateTimeConverter;
import com.zdkj.subway.st.util.SubwayStConstants;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@AllArgsConstructor
@RequestMapping("/swStPlanMonth")
@Api(value = "swStPlanMonth", tags = "车票月度计划")
@Slf4j
public class SwStPlanMonthController {
    private final SwStPlanMonthService swStPlanMonthService;
    private final SwStPlanWeekService swStPlanWeekService;

    @GetMapping("/{id}")
    public R getById(@PathVariable String id) {
        return R.ok(swStPlanMonthService.getById(id));
    }

    @GetMapping("/page/{type}")
    public R<IPage> getDictPage(Page page, SwStPlanMonth swStPlanMonth,@PathVariable String type) {
        swStPlanMonth.setPlanType(type);
        /*LambdaQueryWrapper<SwStPlanMonth> query = Wrappers.query(swStPlanMonth).lambda()
                .eq(SwStPlanMonth::getDisplay, true);*/
        String numbers = swStPlanMonth.getNumbers();
        swStPlanMonth.setNumbers(null);
        QueryWrapper<SwStPlanMonth> query = Wrappers.query(swStPlanMonth);
        query.lambda().eq(SwStPlanMonth::getDisplay, true);
        if(StringUtils.isNotEmpty(numbers)){
            query.lambda().like(SwStPlanMonth::getNumbers,numbers);
        }
        query.orderByDesc("CREATE_TIME");
        return R.ok(swStPlanMonthService.page(page, query));
    }

    @SysLog("新增车票月度计划")
    @PostMapping
    public R save(@Valid @RequestBody SwStPlanMonth swStPlanMonth) {
        PigxUser user = SecurityUtils.getUser();
        swStPlanMonth.setCheckStatus(SubwayStConstants.AUDIT_STATUS_PASS);
        swStPlanMonth.setCreatorId((long) user.getId());
        swStPlanMonth.setCreatorName(user.getUsername());
        swStPlanMonth.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
        return R.ok(swStPlanMonthService.save(swStPlanMonth));
    }

    @SysLog("批量新增车票月度计划")
    @PostMapping("/saveAll")
    public R saveAll(@Valid @RequestBody List<SwStPlanMonth> swStPlanMonthList) {
        PigxUser user = SecurityUtils.getUser();
        for(SwStPlanMonth swStPlanMonth:swStPlanMonthList){
            swStPlanMonth.setCheckStatus(SubwayStConstants.AUDIT_STATUS_PASS);
            swStPlanMonth.setCreatorId((long) user.getId());
            swStPlanMonth.setCreatorName(user.getUsername());
            swStPlanMonth.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
            swStPlanMonthService.save(swStPlanMonth);
        }
        return R.ok(swStPlanMonthList.size());
    }

    @PutMapping("/audit")
    @SysLog("审批车票月度计划")
    public R audit(@Valid @RequestBody SwStPlanMonth swStPlanMonth) {
        PigxUser user = SecurityUtils.getUser();
        swStPlanMonth.setCheckPersonId(user.getId());
        swStPlanMonth.setCheckTime(LocalDateTime.now());
        if(SubwayStConstants.AUDIT_STATUS_PASS.equals(swStPlanMonth.getCheckStatus())){
            swStPlanWeekService.update(Wrappers.<SwStPlanWeek>lambdaUpdate()
                    .eq(SwStPlanWeek::getPlanMonthId, swStPlanMonth.getId())
                    //.apply(" plan_month_id = "+swStPlanMonth.getId())
                    .set(SwStPlanWeek::getDisplay, true));
        }
        return R.ok(swStPlanMonthService.updateById(swStPlanMonth));
    }

    @SysLog("删除车票月度计划")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable String id) {
        return R.ok(swStPlanMonthService.removeById(id));
    }

    @PutMapping("/{id}/decompose")
    @SysLog("分解车票月度计划")
    public R decompose(@PathVariable Long id, @Valid @RequestBody List<SwStPlanWeek> planWeeks) {
        if(!swStPlanMonthService.decompose(id, planWeeks)){
            return R.failed("分解计划明细不能为空/或者已分解完成的计划不能再分解！");
        }else{
            return R.ok(swStPlanMonthService.decompose(id, planWeeks));
        }

    }

    @PutMapping("/{id}/updateDecompose")
    @SysLog("修改分解车票月度计划信息")
    public R updateDecompose(@PathVariable Long id, @Valid @RequestBody List<SwStPlanWeek> planWeeks) {
            return R.ok(swStPlanMonthService.updateDecompose(id, planWeeks));
    }

    @PutMapping
    @SysLog("修改车票月度计划")
    public R updateById(@Valid @RequestBody SwStPlanMonth swStPlanMonth) {
        if(!Objects.equals(swStPlanMonth.getPlanNumberNow(),swStPlanMonth.getPlanNumberOld())) {
            swStPlanMonth.setWhetherStatus("1");
        }else{
            swStPlanMonth.setWhetherStatus("0");
        }
        return R.ok(swStPlanMonthService.updateById(swStPlanMonth));
    }

    @PutMapping("/submit")
    @SysLog("提交车票月度计划")
    public R submit(@Valid @RequestBody List<Long> ids) {
        List<SwStPlanMonth> swStPlanMonths = new ArrayList<>();
        for(long id: ids){
            SwStPlanMonth swStPlanMonth = new SwStPlanMonth();
            swStPlanMonth.setId(id);
            swStPlanMonth.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_PASS);
            swStPlanMonth.setCheckStatus(SubwayStConstants.AUDIT_STATUS_WAIT);
            swStPlanMonths.add(swStPlanMonth);
        }
        return R.ok(swStPlanMonthService.updateBatchById(swStPlanMonths));
    }


    @GetMapping("/export")
    @SysLog("导出车票月度计划")
    public void exportExcel(SwStPlanMonth swStPlanMonth, HttpServletResponse response) throws IOException {
        List<SwStPlanMonth> swStCycleList = swStPlanMonthService.list(Wrappers.query(swStPlanMonth));
        String fileName = URLEncoder.encode("车票月度计划", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SwStPlanMonth.class).registerConverter(new LocalDateTimeConverter())
                .registerConverter(new LocalDateConverter()).sheet("车票月度计划").doWrite(swStCycleList);
    }

    /*@GetMapping("/export")
    @SysLog("导出车票月度计划")
    public void exportExcel(SwStPlanMonth swStPlanMonth, HttpServletResponse response) throws IOException {
        List<SwStPlanMonth> swStCycleList = swStPlanMonthService.list(Wrappers.query(swStPlanMonth));
        IExcelExport excelExport = SpringContextHolder.getBean("commonExcelExport");
        Workbook workbook = excelExport.parse(swStCycleList);
        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("",e);
        }
    }*/

}
